<template>
  <!-- 工单表表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="1200"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="50px"
      v-if="!isNext"
      class="sketch_content"
    >
      <el-row>
        <!--<el-col :span="8">
          <el-form-item label="产品" prop="materialCode">
            <el-input
              v-model="formData.materialCode"
              placeholder="请输入产品"
              clearable
              readonly
              @click="showWorkOrderSelect"
              style="width: 220px"
            >
              <template #append>
                <el-button @click="resetMaterial">清除</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>-->
        <el-col :span="5">
          <el-form-item label="日期" prop="planDate">
            <el-date-picker
              v-model="formData.planDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="">
            <el-button type="primary" @click="getPlanWorkingForm"
              >查询</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            :data="details"
            :key="Math.random"
            border
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              width="70"
              key="id"
              align="center"
            />
            <el-table-column
              label="工序"
              prop="processName"
              min-width="140"
              show-overflow-tooltip
            />
            <el-table-column
              label="班制"
              prop="shiftSystemName"
              min-width="150"
              show-overflow-tooltip
            />
          </el-table>
        </div>
      </el-card>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <dayPlanProductionVersionEdit
      :visible="productionVersionDialog.visible"
      :title="productionVersionDialog.title"
      :data="productionVersionDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="productionVersionDialog.readvisible"
      @change-visible="changeProductionVersion"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
import { productionVersionHook } from "@/views/mes/mesdayplan/hook/productionVersionHook";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MesdayplanView",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
const { api } = productionVersionHook();
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal) {
      //getCommandDay();
    }
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
const isNext = ref(false);
const rules = reactive({
  // materialCode: [{ required: true, message: "请输入产品", trigger: "change" }],
  // planDate: [{ required: true, message: "请选择日期", trigger: "change" }],
  // shiftId: [{ required: true, message: "请选择班次", trigger: "change" }],
  // shiftSystemId: [{ required: true, message: "请选择班制", trigger: "change" }],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  producePlanCode: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  workSequence: "",
  planNum: "",
  planDate: "",
  planQuantity: "",
  productionVersionNumber: "",
  externalCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  planStatus: 0,
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        planDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        producePlanCode,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        materialId,
        materialCode,
        materialName,
        workSequence,
        planNum,
        planDate,
        planQuantity,
        planStatus,
        productionVersionNumber,
        externalCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.producePlanCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.workSequence = "";
  formData.planNum = "";
  formData.planDate = "";
  formData.planQuantity = "";
  formData.planStatus = "0";
  formData.productionVersionNumber = "";
  formData.externalCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  shiftList.value = [];
  details.value = [];
  isNext.value = false;
}
const loading = ref(false);

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    formData.materialId = data.id;
    formData.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  formData.materialId = "";
  formData.materialCode = "";
};

// 获取当前日期yyyymmdd
function getCurrentDate(date) {
  const today = new Date(date);
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
//班制
const shiftSetList = ref([]);
async function getShiftSetList() {
  await request({
    url: "mes/messhiftset/getList",
    method: "post",
    data: { plantId: formData.plantId, enabled: 1 },
  }).then((res) => {
    shiftSetList.value = res.data;
  });
}
function changeShiftSet(index: number, val: any) {
  if (val) {
    processesList.value[index].shiftSystemId = val;
    getShifts(index, val);
  } else {
    processesList.value[index].shiftSystemId = "";
    processesList.value[index].shiftId = "";
  }
}

//班次
const shiftList = ref([]);
async function getShifts(index, val) {
  await request({
    url: "mes/messhiftset/getDetails",
    method: "post",
    data: {
      id: val,
    },
  }).then((res) => {
    // shiftList.value = res.data;
    processesList.value[index].shiftId = res.data[0].shiftId;
  });
}
//获取查询条件下的工单列表
const details = ref([]);
async function getPlanWorkingForm() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (!formData.planDate) {
        ElMessage.error(`请选择日期`);
        return;
      }

      await request({
        url: "/mes/mesplanworkingprocess/getList",
        method: "post",
        data: formData,
      }).then((res: any) => {
        if (res.code == 200) {
          details.value = res.data;
          // if (details.value.length > 0) {
          //   formData.plantId = details.value[0].plantId;
          //   getShiftSetList();
          //   getProcessesList();
          // }
        }
      });
    }
  });
}
const moveUp = (index: number) => {
  const temp = details.value[index];
  details.value.splice(index, 1);
  details.value.splice(index - 1, 0, temp);
};
const shiftDown = (index: number) => {
  const temp = details.value[index];
  details.value.splice(index, 1);
  details.value.splice(index + 1, 0, temp);
};
//生产版本
const productionVersionDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
function productionVersion(row: any) {
  productionVersionDialog.title = "生产版本";
  getProductionVersion(row);
}
function changeProductionVersion(value: boolean) {
  productionVersionDialog.visible = value;
  if (!value) {
    productionVersionDialog.data = {};
  }
}
async function getProductionVersion(row: any) {
  const { data } = await request({
    url: `${api.getDayVersionList}`,
    method: "post",
    data: { planDayId: row.id },
  });
  data[0].planDayId = row.id;
  productionVersionDialog.data = data[0];
  productionVersionDialog.visible = true;
}
//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
const processesList = ref();
async function getProcessesList() {
  await request({
    url: "/mes/mesprocess/getDayPlanCommandList",
    method: "post",
    data: {
      plantId: formData.plantId,
      enabled: 1,
    },
  }).then((res) => {
    res.data.forEach((item: any) => {
      item.shiftSystemId = details.value[0].shiftSystemId;
    });
    processesList.value = res.data;
  });
}
async function getCommandDay() {
  await request({
    url: "/mes/mesdayplan/issueDate",
    method: "post",
    data: {
      plantId: formData.plantId,
      enabled: 1,
    },
  }).then((res) => {
    if (res.code == 200 && res.data) {
      formData.planDate = getCurrentDate(res.data);
    } else {
      ElMessage.error(`没有可下达日期的计划`);
    }
  });
}
</script>
<style lang="scss" scoped>
.sketch_content {
  // 必须有高度 overflow 为自动
  overflow: auto;
  max-height: 500px;
}

// 滚动条的样式,宽高分别对应横竖滚动条的尺寸
.sketch_content::-webkit-scrollbar {
  width: 3px;
}

// 滚动条里面默认的小方块,自定义样式
.sketch_content::-webkit-scrollbar-thumb {
  background: #8798af;
  border-radius: 2px;
}

// 滚动条里面的轨道
.sketch_content::-webkit-scrollbar-track {
  background: transparent;
}
</style>
